package com.news.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.news.common.lang.Result;
import com.news.entity.SysNews;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Leeion
 * @since 2021-12-04
 */
@RestController
//事务回滚注解
@Transactional
@RequestMapping("/sys/news")
public class SysNewsController extends BaseController{

    //按id回显
    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id){
        return Result.succ(sysNewsService.getById(id));
    }

    //分页显示文章内容接口
    @GetMapping("/list")
    public Result list(String title){
        //查询标题
        Page<SysNews> page = sysNewsService.page(getPage(), new QueryWrapper<SysNews>()
                .like(StrUtil.isNotBlank(title),"title",title));
        return Result.succ(page);
    }

    //新增文章接口
    @PostMapping("/save")
    public Result saveNews(@Validated @RequestBody SysNews sysNews){
        sysNews.setCreateTime(LocalDateTime.now());
        sysNews.setUpdateTime(LocalDateTime.now());
        sysNewsService.save(sysNews);
        return Result.succ(sysNews);
    }

    //删除接口
    @PostMapping("/delete")
    public  Result delete(@RequestBody Long[] ids){
        //单个删除和批量删除
        sysNewsService.removeByIds(Arrays.asList(ids));
        return Result.succ("");
    }

    //更新文章接口
    @PostMapping("/update")
    public Result update(@Validated @RequestBody SysNews sysNews){
        sysNews.setUpdateTime(LocalDateTime.now());
        sysNewsService.updateById(sysNews);
        return Result.succ(sysNews);
    }


}
